﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace TST.WebParts
{
    internal sealed class LookupValueConverter : TypeConverter
    {
        public override bool CanConvertTo(
            ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string[]))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(
            ITypeDescriptorContext context,
            CultureInfo culture, object value, Type destinationType)
        {
            if (value != null)
            {
                if (!(value is SPFieldLookupValueCollection || value is SPFieldUserValueCollection || value is string))
                {
                    throw new ArgumentException(
                        "Invalid lookup/user value (collection)", "value");
                }
            }

            if (destinationType == typeof(string[]))
            {
                if (value == null)
                {
                    return null;
                }

                SPFieldLookupValueCollection lookupValues = value as SPFieldLookupValueCollection;
                SPFieldUserValueCollection userValues = value as SPFieldUserValueCollection;
                if (lookupValues == null && userValues == null)
                {
                    return new string[] { ConvertSharePointLinkToValue(value.ToString()) };
                }
                if (lookupValues != null)
                {
                    string[] lookups = new string[lookupValues.Count];
                    for (int i = 0; i < lookupValues.Count; i++)
                    {
                        lookups[i] = lookupValues[i].LookupValue;
                    }
                    return lookups;
                }
                if (userValues != null)
                {
                    string[] users = new string[userValues.Count];
                    for (int i = 0; i < userValues.Count; i++)
                    {
                        users[i] = userValues[i].LookupValue;
                    }
                    return users;
                }
            }

            return base.ConvertTo(context, culture, value,
                destinationType);
        }

        private static string ConvertSharePointLinkToValue(string link)
        {
            return Regex.Replace(link, "^[0-9]+;#", "");
        }
    }
}
